import request from './request'
import qs from "qs";
// 过滤请求参数
const filterParams = (params = {}) => {
    let query = {}
    // 过滤空字符串 undefined null
    const filterEmpty = (value => value !== null && typeof value !== "undefined" && value !== "")
    if (Object.prototype.toString.call(params) === '[object FormData]') {
        // form表单格式单独处理
        params.forEach((item, key) => {
            if (filterEmpty(item)) {
                query[key] = item
            }
        })
        query = qs.stringify(query)
    } else {
        for (let key in params) {
            if (filterEmpty(params[key])) {
                query[key] = params[key]
            }
        }
    }
    return query
}

export function get(url, params, responseType) {
    return new Promise((resolve, reject) => {
        const newParams = filterParams(params)
        request.get(url, {params: newParams, ...responseType}).then(res => {
            resolve(res)
        }).catch(error => {
            reject(error)
        })
    })
}

export function post(url, params, methods = {}) {
    return new Promise((resolve, reject) => {
        request.post(url, params, {
            ...methods,
        }).then(res => {
            resolve(res)
        }).catch(error => {
            reject(error)
        })
    })
}

